package com.sansan.ultrasound_handpad.fragment.process;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;

import com.qmuiteam.qmui.layout.QMUIFrameLayout;
import com.qmuiteam.qmui.skin.QMUISkinHelper;
import com.qmuiteam.qmui.skin.QMUISkinManager;
import com.qmuiteam.qmui.skin.QMUISkinValueBuilder;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.util.QMUIResHelper;
import com.qmuiteam.qmui.widget.QMUIFloatLayout;
import com.qmuiteam.qmui.widget.QMUIProgressBar;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.qmuiteam.qmui.widget.popup.QMUIFullScreenPopup;
import com.qmuiteam.qmui.widget.popup.QMUIPopups;
import com.sansan.ultrasound_handpad.R;
import com.sansan.ultrasound_handpad.base.BaseFragment;
import com.sansan.ultrasound_handpad.manager.QDDataManager;
import com.sansan.ultrasound_handpad.model.QDItemDescription;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author ByLinYus
 * 2020-06-14 14:28:00
 * 扫描后从mes服务器获得程序列表
 */
public class ProcessFragment extends BaseFragment {

    @BindView(R.id.topbar)
    QMUITopBarLayout mTopBar;
    @BindView(R.id.qmuidemo_floatlayout)
    QMUIFloatLayout mFloatLayout;
    @BindView(R.id.rectProgressBar)
    QMUIProgressBar mRectProgressBar;

    private TextView mScanResultTv = null;
    private EditText mScanEditText = null;

    private QDItemDescription mQDItemDescription;

    /*接收扫码器传回来的扫码数据*/
    private BroadcastReceiver mScanReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (mScanEditText != null) {
                mScanEditText.setText("");
            }
            /*扫描数据*/
            byte[] scanData = intent.getByteArrayExtra("barocode");
            /*数据长度*/
            int dataLen = intent.getIntExtra("length", 0);
            /*数据类型*/
            byte dataTyp = intent.getByteExtra("barcodeType", (byte)0);
            /*条码字符串*/
            String barcodeStr = new String(scanData, 0, dataLen);
            if (mScanEditText != null) {
                mScanEditText.setText(barcodeStr);
            }
            if (mScanResultTv != null) {
                mScanResultTv.setText("获得扫描信息!");
            }
        }
    };

    /*初始化标题栏*/
    private void initTopBar() {
        mTopBar.addLeftBackImageButton().setOnClickListener(v -> popBackStack());
        mTopBar.setTitle("程序列表");
    }

    @Override
    protected View onCreateView() {
        View rootView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_process, null);
        ButterKnife.bind(this, rootView);
        /*标题栏*/
        initTopBar();
        /**/
        mRectProgressBar.setProgress(50);
        /**/
        mQDItemDescription = QDDataManager.getInstance().getDescription(this.getClass());
        for (int i = 0; i < 8; i++) {
            addItemToFloatLayout(mFloatLayout);
        }
        mFloatLayout.setOnLineCountChangeListener(new QMUIFloatLayout.OnLineCountChangeListener() {
            @Override
            public void onChange(int oldLineCount, int newLineCount) {
//                Log.i(TAG, "oldLineCount = " + oldLineCount + " ;newLineCount = " + newLineCount);
            }
        });

        return rootView;
    }

    /*添加方块*/
    private void addItemToFloatLayout(QMUIFloatLayout floatLayout) {
        int currentChildCount = floatLayout.getChildCount();

        TextView textView = new TextView(getActivity());
        int textViewPadding = QMUIDisplayHelper.dp2px(getContext(), 4);
        textView.setPadding(textViewPadding, textViewPadding, textViewPadding, textViewPadding);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
        textView.setTextColor(ContextCompat.getColor(getContext(), R.color.qmui_config_color_white));
        textView.setText(String.valueOf(currentChildCount));
        textView.setBackgroundResource(currentChildCount % 2 == 0 ? R.color.app_color_theme_3 : R.color.app_color_theme_6);

        int textViewSize = QMUIDisplayHelper.dpToPx(60);
        ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(textViewSize, textViewSize);

        textView.setOnClickListener(v -> {
            startScanCode(v);
        });

        floatLayout.addView(textView, lp);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getActivity() == null) {
            return;
        }
        /*注册扫描器广播*/
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("urovo.rcv.message");
        getActivity().registerReceiver(this.mScanReceiver, intentFilter);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (getActivity() == null) {
            return;
        }
        /*注销扫描器广播*/
        getActivity().unregisterReceiver(this.mScanReceiver);
    }

    private void startScanCode(View v) {
        QMUISkinValueBuilder builder = QMUISkinValueBuilder.acquire();
        QMUIFrameLayout frameLayout = new QMUIFrameLayout(getContext());
        frameLayout.setBackground(
                QMUIResHelper.getAttrDrawable(getContext(), R.attr.qmui_skin_support_popup_bg));
        builder.background(R.attr.qmui_skin_support_popup_bg);
        QMUISkinHelper.setSkinValue(frameLayout, builder);
        frameLayout.setRadius(QMUIDisplayHelper.dp2px(getContext(), 12));
        int padding = QMUIDisplayHelper.dp2px(getContext(), 20);
        frameLayout.setPadding(padding, padding, padding, padding);

        mScanResultTv = new TextView(getContext());
        mScanResultTv.setLineSpacing(QMUIDisplayHelper.dp2px(getContext(), 4), 1.0f);
        mScanResultTv.setPadding(padding, padding, padding, padding);
        mScanResultTv.setText("正在扫描飞达料盘信息.......");
        builder.clear();
        builder.textColor(R.attr.app_skin_common_title_text_color);
        QMUISkinHelper.setSkinValue(mScanResultTv, builder);
        mScanResultTv.setGravity(Gravity.CENTER);
        int size = QMUIDisplayHelper.dp2px(getContext(), 200);
        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(size, size);
        frameLayout.addView(mScanResultTv, lp);

        FrameLayout editFitSystemWindowWrapped = new FrameLayout(getContext());
        editFitSystemWindowWrapped.setFitsSystemWindows(true);

        int minHeight = QMUIDisplayHelper.dp2px(getContext(), 48);
        QMUIFrameLayout editParent = new QMUIFrameLayout(getContext());
        editParent.setMinimumHeight(minHeight);
        editParent.setRadius(minHeight / 2);
        editParent.setBackground(
                QMUIResHelper.getAttrDrawable(getContext(), R.attr.qmui_skin_support_popup_bg));
        builder.clear();
        builder.background(R.attr.qmui_skin_support_popup_bg);
        QMUISkinHelper.setSkinValue(editParent, builder);

        mScanEditText = new EditText(getContext());
        mScanEditText.setHint("请输入...");
        mScanEditText.setBackground(null);
        builder.clear();
        builder.hintColor(R.attr.app_skin_common_desc_text_color);
        builder.textColor(R.attr.app_skin_common_title_text_color);
        QMUISkinHelper.setSkinValue(mScanEditText, builder);
        int paddingHor = QMUIDisplayHelper.dp2px(getContext(), 20);
        int paddingVer = QMUIDisplayHelper.dp2px(getContext(), 10);
        mScanEditText.setPadding(paddingHor, paddingVer, paddingHor, paddingVer);
        mScanEditText.setMaxHeight(QMUIDisplayHelper.dp2px(getContext(), 100));

        FrameLayout.LayoutParams editLp = new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        editLp.gravity = Gravity.CENTER_HORIZONTAL;
        editParent.addView(mScanEditText, editLp);

        editFitSystemWindowWrapped.addView(editParent,  new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));


        ConstraintLayout.LayoutParams eLp = new ConstraintLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT);
        int mar = QMUIDisplayHelper.dp2px(getContext(), 20);
        eLp.leftToLeft = ConstraintLayout.LayoutParams.PARENT_ID;
        eLp.rightToRight = ConstraintLayout.LayoutParams.PARENT_ID;
        eLp.bottomToBottom = ConstraintLayout.LayoutParams.PARENT_ID;
        eLp.leftMargin = mar;
        eLp.rightMargin = mar;
        eLp.bottomMargin = mar;

        QMUIPopups.fullScreenPopup(getContext())
                .addView(frameLayout, QMUIFullScreenPopup.getOffsetHalfKeyboardHeightListener())
                .addView(editFitSystemWindowWrapped, eLp, QMUIFullScreenPopup.getOffsetKeyboardHeightListener())
                .skinManager(QMUISkinManager.defaultInstance(getContext()))
                .onBlankClick(new QMUIFullScreenPopup.OnBlankClickListener() {
                    @Override
                    public void onBlankClick(QMUIFullScreenPopup popup) {
                        popup.dismiss();
                        Toast.makeText(getContext(), "点击到空白区域", Toast.LENGTH_SHORT).show();
                    }
                })
                .onDismiss(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        Toast.makeText(getContext(), "onDismiss", Toast.LENGTH_SHORT).show();
                    }
                })
                .show(v);
    }
}
